package com.icim.rest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.icim.common.LoadHistoryConfig;
import com.icim.rabbitmq.util.RabbitmqManager;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.ShutdownSignalException;

@Controller
public class Export2FileController {

	private static Logger logger = Logger.getLogger(LoadHistoryMainController.class);

	private final static String END_PIXEL = "\r\n";
	@Autowired
	AmqpTemplate amqpTemplate;

	@Resource
	RabbitAdmin rabbitAdmin;

	@Resource
	Queue historyQueue;
	@Resource
	CachingConnectionFactory rabbitConnFactory;

	@Autowired
	RabbitmqManager rabbitmqManager;

	@Resource
	LoadHistoryConfig loadHistoryConfig;

	private void exportHisQueueMessageToFile(String queueName, FileWriter fw) throws IOException {
		List<String> exportQueueMessageList = new ArrayList<String>();
		StringBuffer buffer = new StringBuffer();
		String message;
		int exportCnt = 0;
		while (true) {

			message = rabbitmqManager.recieveMessage(queueName);

			if (message == null) {
				logger.info("export[" + exportCnt + "]queues successful");
				break;
			}

			buffer.setLength(0);
			buffer.append(message).append(END_PIXEL);

			fw.append(buffer.toString());

			exportQueueMessageList.add(message);
			exportCnt++;
		}
		fw.flush();
		fw.close();
		for (String exportedMessage : exportQueueMessageList) {
			rabbitmqManager.setMessage(queueName, exportedMessage);
		}
		logger.info("rePut[" + exportCnt + "]queues successful");
	}


	@RequestMapping(value = "/export2File.do")
	@ResponseBody
	public void export2File(HttpServletRequest request, HttpServletResponse response, String queueName)
			throws ShutdownSignalException, ConsumerCancelledException, InterruptedException {

		if(StringUtils.isEmpty(queueName)){
			return;
		}
		String exportPath = loadHistoryConfig.getExportFilePath();
		try {
			File file = new File(exportPath + System.currentTimeMillis() + ".txt");
			FileWriter fw = new FileWriter(file);

			exportHisQueueMessageToFile(queueName, fw);


			byte[] baos = FileUtils.readFileToByteArray(file);
			
			file.getAbsoluteFile().delete();
			
			response.reset();
			response.setContentType("text/html;charset=utf-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".txt");
			response.setContentLength(baos.length);
			
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(baos);
			toClient.flush();
			toClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


}
